<template>
  <div>
    <el-tag
      v-for="tag in deviceTagList"
      :key="tag"
      size="medium"
      class="mr-1"
      closable
      @close="deleteTagDevice(tag)"
    >
      {{ tag.name }}
    </el-tag>
    <el-select v-if="showTagSelect" v-model="tagId" @change="tagSelect">
      <el-option
        v-for="item in tagList"
        :key="item.tagId"
        :label="item.name"
        :value="item.tagId"
      />
    </el-select>
    <el-button v-else type="primary" icon="el-icon-plus" @click="showTagSelect = true" />
  </div>
</template>

<script>
import {
  insertTagDevice,
  deleteTagDevice,
  listTagDeviceTagByUser
} from '@/api/iot/iotTagDeviceApi'
import { listTag } from '@/api/iot/iotTagApi'
import { successNotice } from '@/util/common'
export default {
  name: 'TagDevice',
  props: {
    device: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      showTagSelect: false,
      tagList: [],
      deviceTagList: []
    }
  },
  watch: {
    device: {
      deep: true,
      handler() {
        this.listTag()
      }
    }
  },
  created() {
    this.listTag()
  },
  methods: {
    tagSelect() {
      insertTagDevice({
        tagId: this.tagId,
        deviceId: this.device.deviceId
      }).then(res => {
        const { code } = res
        if (code === '200') {
          this.listTagDeviceTagByUser()
          this.showTagSelect = false
        }
      })
    },
    listTag() {
      listTag({

      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.tagList = data
          this.listTagDeviceTagByUser()
        } else {
          this.tagList = []
        }
      })
    },
    deleteTagDevice(tag) {
      deleteTagDevice({
        id: tag.id
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listTagDeviceTagByUser()
      })
    },
    listTagDeviceTagByUser() {
      listTagDeviceTagByUser({
        deviceId: this.device.deviceId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.deviceTagList = data
        } else {
          this.deviceTagList = []
        }
      })
    }
  }
}
</script>


